from django.shortcuts import render
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, GenericAPIView, UpdateAPIView, RetrieveAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cookie_redis_cart
from .serializers import RegisterUserSerializer, EmailSendSerializer, UserInfoSerializer, AddressSerializer, AddressTitleSerializer
from .models import User
from rest_framework.views import APIView


# Create your views here.

class CheckUserNameView(APIView):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()

        data = {
            'count': count,
        }

        return Response(data, status=status.HTTP_200_OK)


# 检查手机号是否已经注册
class CheckPhoneView(APIView):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'count': count,
        }
        return Response(data, status=status.HTTP_200_OK)


class RegisterUserView(CreateAPIView):
    serializer_class = RegisterUserSerializer

    # 只继承GenericAPIView
    # def post(self, request):
    #
    #     dict_data = request.data
    #
    #     # 创建序列化器
    #     serializer = self.get_serializer(data=dict_data)
    #
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 数据入库
    #     serializer.save()
    #     return Response(serializer.data, status=status.HTTP_201_CREATED)


class UserInfoView(RetrieveAPIView):
    serializer_class = UserInfoSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

    # 仅仅继承GenericAPIView
    # def get(self, request):
    #     # 获取参数
    #     user = self.get_object()
    #
    #     serializer = self.get_serializer(instance=user)
    #
    #     return Response(serializer.data)
    #


class EmailSendView(UpdateAPIView):
    serializer_class = EmailSendSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

    # 仅仅继承GenericAPIView
    # def put(self, request):
    #     # 获取数据
    #     dict_data = request.data
    #     user = self.get_object()
    #
    #     # 获取序列化器
    #     serializer = self.get_serializer(data=dict_data, instance=user)
    #     # 校验, 入库
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #     return Response(serializer.data)


class EmailActiveView(APIView):
    def get(self, request):
        token = request.query_params.get('token')
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 解密
        user = User.decode_token(token)

        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 修改邮件激活状态
        user.email_active = True
        user.save()

        return Response(status=status.HTTP_200_OK)


class AddressView(mixins.UpdateModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, GenericViewSet):
    serializer_class = AddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.address.filter(is_deleted=False)

    def list(self, request):
        queryset = self.get_queryset()
        serializer = self.get_serializer(instance=queryset, many=True)
        return Response({
            'addresses': serializer.data,
            'limit': 20,
            'default_address_id': request.user.default_address_id,
        })

    def create(self, request, *args, **kwargs):
        count = request.user.address.filter(is_deleted=False).count()

        if count >= 21:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        return super(AddressView, self).create(request, *args, **kwargs)

    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        request.user.default_address_id = pk
        request.user.save()

        return Response(status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk):
        # address = request.user.address

        dict_data = request.data
        address = self.get_object()

        serializer = AddressTitleSerializer(instance=address, data=dict_data)

        serializer.is_valid()
        serializer.save()
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()

        return Response(status=status.HTTP_204_NO_CONTENT)


class UserObtainJSONWebToken(ObtainJSONWebToken):
    """
    重写登陆方法,合并购物车数据
    """
    def post(self, request, *args, **kwargs):
        # 调用父类方法
        response = super().post(request, *args, **kwargs)
        # 获取序列化器
        serializer = self.get_serializer(data=request.data)
        # 判断是否认证成功
        if serializer.is_valid():
            # 获取user对象
            user = serializer.validated_data.get('user')
            # 合并购物车
            response = merge_cookie_redis_cart(request, user, response)

        return response














